<!-- 高级搜索 -->
<template>
  <div ref="searchbarRef" class="search-area">
    <px-input
      ref="searchInputRef"
      v-model="searchContent"
      placeholder="请输入要搜索的内容"
      class="input-with-select"
      clearable
      @focus="inputFocus"
      @blur="inputBlur"
      @change="inputChange"
      @keydown.enter="search"
    />
    <div v-show="isShow" ref="searchListRef" v-loading="loading" class="search-drop-menu">
      <div class="search-history">
        <div v-if="showHistory">
          <div class="search-title">
            <div>
              <span v-if="searchHistoryList.length > 0">历史记录</span>
              <span v-else>暂无历史记录</span>
            </div>
            <div v-show="searchHistoryList.length > 0" class="clear-history" @click="clearhistory">清空</div>
          </div>
          <div class="history-content">
            <ul v-for="item in searchHistoryList" :key="item">
              <li @click="searchhistory(item)">{{ item }}</li>
            </ul>
          </div>
        </div>
        <div v-else>
          <px-empty v-if="searchList.length === 0" />
          <ul v-for="item in searchList" v-else :key="item.id">
            <li class="search-item" @click="searchConfirm(item)">
              <div>
                <FolderIcon v-if="item.docType === 'F'" class="folder-icon" />
                <FileIcon v-else class="folder-icon" />
              </div>
              <div>
                <p>
                  <span class="folder-name">{{ item.name }}</span>
                </p>
                <p>
                  <span class="folder-path">所在路径：{{ item.path }}</span>
                </p>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, onBeforeUnmount } from "vue";
import { PxMessage } from "px-ui";
import FolderIcon from "@/assets/svg/knowledge/folder.svg?component";
import FileIcon from "@/assets/svg/knowledge/file.svg?component";
import { advancedSearchAPI } from "@/api/knowledge/documentManage";

const emits = defineEmits(["search"]);

const searchbarRef = ref(null);
const searchInputRef = ref(null);
const searchListRef = ref(null);
const state = reactive({
  searchContent: "", //搜索内容
  isShow: false,
  searchHistoryList: [], //搜索历史列表
  loading: false,
  searchList: [],
  showHistory: true
});
const { searchContent, isShow, searchHistoryList, loading, searchList, showHistory } = toRefs(state);

onMounted(() => {
  document.addEventListener("click", handleClickOutside);
});

onBeforeUnmount(() => {
  document.removeEventListener("click", handleClickOutside);
});

const handleClickOutside = e => {
  const divToHide = searchbarRef.value;
  if (divToHide && !divToHide.contains(e.target)) {
    state.isShow = false;
    state.showHistory = true;
  }
};

const inputBlur = () => {
  // state.isShow = false;
  // state.showHistory = true;
};

const inputFocus = () => {
  //获取用户搜索历史
  let list = JSON.parse(localStorage.getItem("search_history_list")) || [];
  state.searchHistoryList = list;
  state.isShow = true;
};

const inputChange = val => {
  if (val === "") {
    state.isShow = true;
  }
};

// 点击搜索历史
const searchhistory = val => {
  searchInputRef.value.focus();
  state.searchContent = val;
  search();
};

//远程搜索
const search = async () => {
  if (state.searchContent == "") {
    PxMessage.error("请输入搜索内容");
    return;
  }
  state.searchHistoryList.unshift(state.searchContent);
  //判断列表长度是否大于10 如果大于了就删除一个最旧的
  while (state.searchHistoryList.length > 10) {
    state.searchHistoryList.pop();
  }
  //保存到本地存储
  localStorage.setItem("search_history_list", JSON.stringify([...new Set(state.searchHistoryList)]));
  state.isShow = true;
  state.showHistory = false;
  state.loading = true;
  const res = await advancedSearchAPI({ name: state.searchContent });
  state.loading = false;
  state.searchList = res;
};

const searchConfirm = item => {
  state.searchContent = item.name;
  state.isShow = false;
  state.showHistory = true;
  emits("search", item.parentId === null ? item.id : item.parentId);
};

//清除历史记录
const clearhistory = () => {
  state.searchHistoryList = [];
  localStorage.removeItem("search_history_list");
};

const clearInput = () => {
  searchInputRef.value.clear();
  state.isShow = false;
};

defineExpose({
  clearInput
});
</script>

<style lang="scss" scoped>
.search-area {
  position: relative;
  width: 300px;
}

.search-drop-menu {
  position: absolute;
  top: 39px;
  left: 0;
  z-index: 9999; /* 设置一个很高的值确保在最上层 */
  box-sizing: border-box;
  width: 300px;
  height: auto;
  min-height: 200px;
  max-height: 350px;
  padding: 8px 0 12px;
  overflow-y: auto;
  font-size: 14px;
  font-weight: 400;
  color: #555666;
  text-align: left;
  background: #fff;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 0 10px 2px rgb(0 0 0 / 6%);
}

.search-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 32px;
  padding: 0 8px;
}

.clear-history {
  color: #3b82f6;
  cursor: pointer;
}

.history-content ul li {
  width: 100%;
  height: 32px;
  padding: 0 16px;
  line-height: 32px;
  cursor: pointer;

  &:hover {
    color: #3b82f6;
    background: #f8f8f8;
  }
}

.search-item {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 4px 16px;
  cursor: pointer;

  &:hover {
    background: #f8f8f8;
  }

  .folder-icon {
    margin-right: 4px;
  }

  .folder-name {
    font-size: 12px;
  }

  .folder-path {
    font-size: 12px;
    color: rgb(0 0 0 / 60%);
  }
}
</style>
